package cn.zhuizikejithreeig.com.passenger;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import cn.zhuizikejithreeig.com.adapter.LaYaListAdapter;
import cn.zhuizikejithreeig.com.been.BoothBeen;
import cn.zhuizikejithreeig.com.brodcat.BlothBaocast;
import cn.zhuizikejithreeig.com.brodcat.BlothClickeView;
import cn.zhuizikejithreeig.com.brodcat.BlothView;
import cn.zhuizikejithreeig.com.utils.ToastMake;

public class LanYaActivity extends BasicActivity implements BlothView ,BlothClickeView{
    private BluetoothAdapter mBluetoothAdapter;
    private BlothBaocast mBlothBaocast;
    private static final UUID BTMODULEUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private LaYaListAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    System.out.println("蓝牙已经连接成功了");
                    break;
                case 3:

                    break;
            }
        }
    };
    private BluetoothSocket mBluetoothSocket;

    @Override
    protected boolean actionBarNeedGoon() {
        return false;
    }

    @Override
    public int setContView() {
        return R.layout.activity_lan_ya;
    }

    @Override
    protected int setHandIndexShow() {
        return 0;
    }

    @Override
    protected void initToDo() {

    }

    @Override
    protected void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager manager = new LinearLayoutManager(LanYaActivity.this);
        mRecyclerView.setLayoutManager(manager);


        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);//180可见时间 单位s
        startActivity(intent);

    }

    @Override
    protected void netChengedListen(int netMobile) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBlothBaocast == null) {
            mBlothBaocast = new BlothBaocast(LanYaActivity.this);
        }
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
        registerReceiver(mBlothBaocast, intent);
    }

    public void onClick(View view) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(LanYaActivity.this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                getSinglePermission(Manifest.permission.ACCESS_COARSE_LOCATION);
                //向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {
                    ToastMake.showToast("自Android 6.0开始需要打开位置权限才可以搜索到Ble设备");
                }
                return;
            }
        }
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        //1.设备不支持蓝牙，结束应用
        if (mBluetoothAdapter == null) {
            ToastMake.showToast("该设备不支持蓝牙");
            return;
        }
        //2.判断蓝牙是否打开
        //true表示已经开启，false表示蓝牙并没启用
        if (!mBluetoothAdapter.enable()) {
            mBluetoothAdapter.enable();
        }
        //如果当前发现了新的设备，则停止继续扫描，当前扫描到的新设备会通过广播推向新的逻辑
        if (mBluetoothAdapter.isDiscovering()) {
            if (mBluetoothAdapter != null) {
                mBluetoothAdapter.cancelDiscovery();
            }
        }
        //开始搜索
        mBluetoothAdapter.startDiscovery();
    }
    /**
     * 反注册广播取消蓝牙的配对
     */

    @Override
    protected void onPause() {
        super.onPause();
        if (mBluetoothAdapter != null)
            mBluetoothAdapter.cancelDiscovery();
    }
    @Override
    public void getListNameAdree(List<BoothBeen> nameAndPostins) {
        String connectBt = getConnectBt();

        if (connectBt!=null){
            System.out.println("当前已经连接的蓝牙设备是"+connectBt);
        }

        for (int i = 0; i < nameAndPostins.size(); i++) {

            nameAndPostins.get(i).setCencent(false);

            if (TextUtils.equals( nameAndPostins.get(i).getName(), connectBt)) {
                nameAndPostins.get(i).setCencent(true);
            }

        }

        if (mAdapter==null) {

            mAdapter = new LaYaListAdapter(nameAndPostins,LanYaActivity.this);
            mRecyclerView.setAdapter(mAdapter);

        }else {
            mAdapter.notifyDataSetChanged();
        }
    }

    //检查已连接的蓝牙设备
    private String  getConnectBt() {
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {//得到蓝牙状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {

//                LogUtil.i("BluetoothAdapter.STATE_CONNECTED");

                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
//                LogUtil.i("devices:"+devices.size());

                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);

                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);

                    if (isConnected) {
//                        LogUtil.i("connected:"+device.getAddress());
                        return device.getAddress();
//                        return device.getName();
                    }else {
                        ToastMake.showToast("网络连接失败，请检查网络");
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    //点击某条条目进行连接
    @Override
    public void sendUri(final BluetoothDevice address) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (address.getBondState() == BluetoothDevice.BOND_NONE) {
                    //如果这个设备取消了配对，则尝试配对
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        address.createBond();
                    }
                } else if (address.getBondState() == BluetoothDevice.BOND_BONDED) {
                    //如果这个设备已经配对完成，则尝试连接
                    connect(address, handler);
                }
            }
        }).start();

    }
    /**
     * 尝试连接一个设备，子线程中完成，因为会线程阻塞
     *
     * @param address 蓝牙设备对象
     * @param handler 结果回调事件
     * @return
     */
    private void connect(BluetoothDevice address, Handler handler) {


            try {
                //通过和服务器协商的uuid来进行连接
                mBluetoothSocket = address.createRfcommSocketToServiceRecord(BTMODULEUUID);
                if (mBluetoothSocket != null)
                 //全局只有一个bluetooth，所以我们可以将这个socket对象保存在appliaction中
                    CompontApplayCation.bluetoothSocket = mBluetoothSocket;
                //通过反射得到bltSocket对象，与uuid进行连接得到的结果一样，但这里不提倡用反射的方法
                //mBluetoothSocket = (BluetoothSocket) btDev.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(btDev, 1);

                System.out.println("开始连接...");
                //在建立之前调用
                if (mBluetoothAdapter.isDiscovering())
                    //停止搜索
                    mBluetoothAdapter.cancelDiscovery();
                //如果当前socket处于非连接状态则调用连接
                if (!mBluetoothSocket.isConnected()) {
                    //你应当确保在调用connect()时设备没有执行搜索设备的操作。
                    // 如果搜索设备也在同时进行，那么将会显著地降低连接速率，并很大程度上会连接失败。
                    mBluetoothSocket.connect();
                }
                System.out.println("已经链接");
                if (handler == null) return;
                //结果回调
                Message message = new Message();
                message.what = 1;
                message.obj = address;
                handler.sendMessage(message);
            } catch (Exception e) {
                System.out.println("...链接失败");
                try {
                    mBluetoothSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
    }
    /**
     * 这个操作应该放在子线程中，因为存在线程阻塞的问题
     */
    public void run(Handler handler) {
        //服务器端的bltsocket需要传入uuid和一个独立存在的字符串，以便验证，通常使用包名的形式
        BluetoothServerSocket bluetoothServerSocket = null;
        try {
         bluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("com.zhuizikejithreeig.cn.threeigkeji", BTMODULEUUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                //注意，当accept()返回BluetoothSocket时，socket已经连接了，因此不应该调用connect方法。
                //这里会线程阻塞，直到有蓝牙设备链接进来才会往下走
//                socket = getBluetoothServerSocket().accept();
                BluetoothSocket socket = bluetoothServerSocket.accept();
                if (socket != null) {
//                    BltAppliaction.bluetoothSocket = socket;
                    //回调结果通知
                    Message message = new Message();
                    message.what = 3;
                    message.obj = socket.getRemoteDevice();
                    handler.sendMessage(message);
                    //如果你的蓝牙设备只是一对一的连接，则执行以下代码
                    bluetoothServerSocket.close();
                    //如果你的蓝牙设备是一对多的，则应该调用break；跳出循环
                    //break;
                }
            } catch (IOException e) {
                try {
                    bluetoothServerSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                break;
            }
        }
    }
}
